package com.platform.common.web.intercepors;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.platform.common.config.PlatformConfig;
import com.platform.common.web.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 演示拦截器
 */
@Slf4j
@Component
public class DemoInterceptor implements HandlerInterceptor {

    private ObjectMapper mapper = new ObjectMapper();

    private static final List<String> array = Arrays.asList("/updPass",
            "/sys/menu/add", "/sys/menu/edit", "/sys/menu/delete", "/sys/menu/copy");

    @Autowired
    private PlatformConfig platformConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (!PlatformConfig.YES.equals(platformConfig.getDemo())) {
            return true;
        }
        if (!array.contains(request.getRequestURI())) {
            return true;
        }
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        String json = mapper.writeValueAsString(AjaxResult.fail("演示模式下不能操作"));
        response.getWriter().print(json);
        return false;
    }
}
